import { defineStore } from 'pinia';
import type { CategoryMapT, DocMenuConfigT, DocMenuT } from '@/@types/type-doc-menu.ts';
import type { LocaleT } from '@/@types/type-locale.ts';
import { computed, onMounted, ref, watch } from 'vue';
import { MENU_MAP, MENU_KEYS } from '@/config/menu';
import { useLocale } from '@/composables/useLocale.ts';
import { inBrowser, useData, useRoute } from 'vitepress';
import docTypeInfo from '@/config/doc-type.ts';
import type { DocMenuNodeT } from '@/utils/tree.ts';
import { DocMenuTree } from '@/utils/tree.ts';


/**
 * 会议相关信息
 */
export const useMenuStore = defineStore('menu', () => {
  const { locale } = useLocale();
  const { page } = useData();
  const route = useRoute();

  const normalizeConfig = (data: Array<DocMenuConfigT>, language: LocaleT, parent: DocMenuT = null): Array<DocMenuT> => {
    return data.map((item, idx) => ({
      id: item.id,
      label: item.label[language] || item.label,
      href: item.href?.[language] || item.href,
      children: item.children ? normalizeConfig(item.children, language, item) : undefined,
      parent: parent,
    }));
  };

  const categoryMap = computed(() => {
    const map: CategoryMapT = {};
    MENU_KEYS.forEach((key) => {
      map[key] = {
        config: normalizeConfig(MENU_MAP[key], locale.value),
        base: '/docs/' + locale.value + '/' + key
      };
    });
    return map;
  })

  const currentCategory = computed(() => {
    const filePath = page.value.filePath;
    const pathList = filePath.split('/');
    const category = pathList[1];
    if (categoryMap.value[category]) {
      return categoryMap.value[category];
    } else {
      return categoryMap.value['development'];
    }
  });

  const docPath = ref('');
  const docType = ref('');
  const currentDocType = ref('');
  // 面包屑参数
  const breadCrumbParams = ref<Array<DocMenuNodeT>>([]);
  const lastBread = ref(null);


// n叉树
  const tree = computed(() => {
    return new DocMenuTree(currentCategory.value.config, currentCategory.value.base);
  });

  const getData = () => {
    if (!inBrowser) {
      return ;
    }
    const path = decodeURIComponent(route.path)
    docPath.value = path.split('/')[2] + '/' + path.split('/')[3];
    currentDocType.value = path.split('/')[3];
    const find = docTypeInfo.find((item) => item.id === currentDocType.value);
    if (find) {
      docType.value = find.label[locale.value];
    } else {
      docType.value = currentDocType.value;
    }

    const filePath = page.value.filePath;

    const url = `/docs/${ filePath }`.replace(/\.md$/, '');
    if (url) {

      breadCrumbParams.value = [];

      let node = tree.value.getNodeByHref(tree.value.root, url);
      if (node) {
        while (node && node.depth !== 0 && node.parent) {
          breadCrumbParams.value.unshift(node);
          node = node?.parent;
        }
      }
      lastBread.value = breadCrumbParams.value.at(-1);
    }
  }

  watch(
    () => [route.path, currentCategory.value.config],
    () => {
      getData();
    }
  );

  onMounted(() => {
    getData();
  });

  return {
    currentCategory: currentCategory,
    categoryMap: categoryMap,
    lastBread: lastBread,
    docPath: docPath,
    docType: docType,
    currentDocType: currentDocType,
    breadCrumbParams: breadCrumbParams,
    tree: tree
  }
})